﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;

namespace CrankShaftAnalysisSystem.SubForm
{
    public partial class FormOfflineHandle : Form
    {
        public FormOfflineHandle()
        {
            InitializeComponent();
        }

        private void btnSetUUID_Click(object sender, EventArgs e)
        {
            DataStorage.uuid = txtUUID.Text;
        }

        private void FormOfflineHandle_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            Hide();
        }

        private void btnCalculateAgain_Click(object sender, EventArgs e)
        {
            string _path = txtPath.Text;
            if (!Directory.Exists(_path))
                return;
            var files = Directory.GetFiles(_path, "*.csv");
            var log_path = Path.Combine(_path, "history.csv");
            var parts = files.Select(s => Path.GetFileNameWithoutExtension(s)).ToArray();
            var handler = new CrankShaftResultHandler.ResultHandler();
            handler.LoadRefrenceAndConfig(MeasureSystem.MeasureSetting.RefrenceReport);
            for (int i=0;i<parts.Length;i++)
            {
                DataStorage.uuid = parts[i];
                if (!parts[i].Contains("RV"))
                    continue;
                var ret = handler.ReadCSV(Path.Combine(_path, files[i]));
                if (ret == null) continue;
                handler.Deal().SaveResult(DataStorage.uuid, log_path);
                progressDeal.Value = i *100 / parts.Length;
            }
            progressDeal.Value = 100;
            handler.WriteCalibrationHeader(log_path);
            MessageBox.Show("计算结束");
        }

        private void btnChooseReference_Click(object sender, EventArgs e)
        {
            DialogResult ret = openRefrenceDialog.ShowDialog();
            if (ret != DialogResult.OK)
                return;
            string file_name = openRefrenceDialog.FileName;
            txtRefrenceReport.Text = file_name;
            //var part_name = Path.GetFileNameWithoutExtension(file_name);            
        }

        private void btnCalibrateAgain_Click(object sender, EventArgs e)
        {
            // 文件名全称必定大于4
            if (txtRefrenceReport.Text.Length < 5)
                return;
            var ret = MeasureSystem.Instance.CalibrateSystem(txtRefrenceReport.Text);
            if (ret)
                MessageBox.Show("重新标定成功");
            else
                MessageBox.Show("标定失败", "ERROR"  ,MessageBoxButtons.OK , icon: MessageBoxIcon.Error);
        }
    }
}
